"""
Copyright (c) 2012, Nimar S. Arora, nimar.arora@gmail.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import numpy as np

AVG_EARTH_RADIUS_KM = 6371.0

# strip away any trailing errors which can cause arccos to return nan
# if mat is -1.0000000000000002 for example
def safe_acos(mat):
  return np.where(mat > 1, 0., np.where(mat < -1, np.pi, np.arccos(mat)))

def dist_deg(loc1, loc2):
  """
  Compute the great circle distance between two point on the earth's surface
  in degrees.
  loc1 and loc2 are pairs of longitude and latitude
  >>> int(dist_deg((10,0), (20, 0)))
  10
  >>> int(dist_deg((10,0), (10, 45)))
  45
  >>> int(dist_deg((-78, -12), (-10.25, 52)))
  86
  >>> dist_deg((132.86521, -0.45606493), (132.86521, -0.45606493)) < 1e-4
  True
  >>> dist_deg((127.20443, 2.8123965), (127.20443, 2.8123965)) < 1e-4
  True
  """
  lon1, lat1 = loc1
  lon2, lat2 = loc2

  return np.degrees(safe_acos(np.sin(np.radians(lat1))
                              * np.sin(np.radians(lat2))
                              + np.cos(np.radians(lat1))
                              * np.cos(np.radians(lat2))
                              * np.cos(np.radians(lon2 - lon1))))

def dist_km(loc1, loc2):
  """
  Returns the distance in km between two locations specified in degrees
  loc = (longitude, latitude)
  """
  lon1, lat1 = loc1
  lon2, lat2 = loc2
  
  return np.radians(dist_deg(loc1, loc2)) * AVG_EARTH_RADIUS_KM


class TTTable:
  def __init__(self, tttable_file):
    self.dist_list, self.ttime_list = [], []
    fp = open(tttable_file)
    rows = fp.readlines()
    # skip the first header line
    for row in rows[1:]:
      dist, ttime = row.split()[:2]
      self.dist_list.append(float(dist))
      self.ttime_list.append(float(ttime))

    self.MAX_TRAVEL_TIME = self.ttime_list[-1]
    self.MAX_DISTANCE = self.dist_list[-1]
  
  def lookup(self, distkm):
    assert(distkm >= self.dist_list[0] and distkm <= self.dist_list[-1])

    if distkm == self.dist_list[0]:
      return self.ttime_list[0]
    elif distkm == self.dist_list[-1]:
      return self.ttime_list[-1]
    
    # binary search to find the distance
    low, high = 0, len(self.dist_list)

    while low < (high - 1):
      mid = (low + high) / 2
      if distkm < self.dist_list[mid]:
        high = mid
      elif distkm > self.dist_list[mid]:
        low = mid
      else:
        return self.ttime_list[mid]

    # interpolate between low and high
    return (self.ttime_list[low]
            + (((self.ttime_list[high] - self.ttime_list[low])
                /(self.dist_list[high] - self.dist_list[low]))
               * (distkm - self.dist_list[low])))
